import os
import random

def generate_bin_file(path="./data/test.bin", size=188*1024*1024):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "wb") as f:
        f.write(os.urandom(size))

def compare_bin_files(file1, file2):
    """比较两个bin文件内容是否一致，并统计差异字节数"""
    bufsize = 4096 * 16
    diff_count = 0
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        while True:
            b1 = f1.read(bufsize)
            b2 = f2.read(bufsize)
            if not b1 and not b2:
                break
            # 处理文件长度不一致的情况
            if b1 != b2:
                minlen = min(len(b1), len(b2))
                # 统计相同长度部分的差异
                for i in range(minlen):
                    if b1[i] != b2[i]:
                        diff_count += 1
                # 统计多余部分的差异
                diff_count += abs(len(b1) - len(b2))
            if not b1 or not b2:
                break
    identical = (diff_count == 0)
    return identical, diff_count

if __name__ == "__main__":
    # generate_bin_file()
    # print("Generated 188MB random bin file at ./data/test.bin")
    # 示例用法
    file1 = './data/test.bin'
    file2 = './data/received.bin'
    size1 = os.path.getsize(file1)
    size2 = os.path.getsize(file2)
    print(f"{file1} size: {size1} bytes")
    print(f"{file2} size: {size2} bytes")
    result, diff = compare_bin_files(file1, file2)
    if result:
        print("Files are identical!")
    else:
        print(f"Files differ! Difference bytes: {diff}")
